home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 18485 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  94 lines

  1. Path: linus.mitre.org!linus!rhl
  2. From: rhl@jambo.mitre.org (Roger Lincoln)
  3. Newsgroups: comp.lang.c++
  4. Subject: Compiling templates
  5. Date: 21 Apr 1996 01:02:34 GMT
  6. Organization: The MITRE Corporation
  7. Message-ID: <RHL.96Apr20210234@jambo.mitre.org>
  8. NNTP-Posting-Host: jambo.mitre.org
  9.  
  10.  
  11. I'm having trouble getting g++ to compile a templated class into a
  12. separate object module and link to it from another.  Here's a simple
  13. sample, can anyone spot what I'm doing wrong?
  14.  
  15.  
  16. -- file: thing.hxx --
  17. template <class T>
  18. class Thing
  19. {
  20. public:
  21.   Thing(T p);
  22.   T GetThing();
  23. protected:
  24.   T theThing;
  25. };
  26.  
  27.  
  28. -- file: thing.cxx --
  29. #include "thing.hxx"
  30.  
  31. template <class T>
  32. Thing<T>::Thing(T p)
  33. {
  34.   theThing = p;
  35. }
  36.  
  37.  
  38. template <class T>
  39. T Thing<T>::GetThing()
  40. {
  41.   return (theThing);
  42. }
  43.  
  44.  
  45.  
  46. -- file: test.cxx --
  47. #include <stream.h>
  48. #include "thing.hxx"
  49.  
  50. main() {
  51.   int i = 10;
  52.   Thing<int> t(i);
  53.   cout << "thing = " << t.GetThing();
  54. }
  55.  
  56.  
  57. -- file: Makefile --
  58. test: test.o thing.o
  59.     g++ -o test test.o thing.o
  60.  
  61. test.o: test.cxx thing.hxx
  62.     g++ -c test.cxx
  63.  
  64. thing.o: thing.cxx thing.hxx 
  65.     g++ -c thing.cxx
  66.  
  67.  
  68.  
  69. Everything compiles fine, but when it tries to link it is unable to
  70. "find" the templated class...
  71.  
  72.  
  73. g++ -c test.cxx
  74. g++ -o test test.o thing.o
  75. Undefined     first referenced
  76.  symbol           in file
  77. GetThing__t5Thing1Zi                test.o
  78. __t5Thing1Zii                       test.o
  79. _._t5Thing1Zi                       test.o
  80. ld: fatal: Symbol referencing errors. No output written to test
  81. make: *** [test] Error 1
  82.  
  83.  
  84. I end up having to include the class implementation in any module that
  85. uses it, but this defeats the purpose of separate compilation units.
  86. Am I doing something wrong or does g++ not handle templates correctly?
  87.  
  88. -- 
  89.  \_____   \__ \__  \__     |  Roger H. Lincoln      | The activity of        |
  90.  \__ \__  \__ \__  \__     |  MITRE Corp.           | "debugging" ends when  |
  91.  \_____   \______  \__     |  Bedford, MA           | people get tired of    |
  92.  \__ \__  \__ \__  \_____  |  rhl@mitre.org         | doing it, not when the |
  93.  \__  \__ \__ \__  \_____  |  PGP key available     | bugs are removed.      |
  94.